package top.stacktrace.gateway.config.auth;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import top.stacktrace.gateway.service.LoginService;

import java.util.Objects;

@Slf4j
@Component
public class TokenAuthConverter implements ServerAuthenticationConverter {
    @Autowired
    private LoginService loginService;
    @Override
    public Mono<Authentication> convert(ServerWebExchange exchange) {
        String token = exchange.getRequest().getHeaders().getFirst("token");
        Token t = loginService.getToken(token);
        if(Objects.isNull(t)){
            t = new Token("");
            t.setAuthenticated(false);
        }else{
            exchange.getRequest().mutate().header("userid",String.valueOf(t.getUserid())).build();
        }
        return Mono.just(t);
    }
}
